import 'package:dali_ng_pera/mob/dnp_mob.dart';
import 'package:dali_ng_pera/page/browser/dnp_browser_page.dart';
import 'package:dali_ng_pera/page/certification/dnp_identity_information_page.dart';
import 'package:dali_ng_pera/page/certification/utils/dnp_certification_jump_utils.dart';
import 'package:dali_ng_pera/page/widget/dnp_lifecycle_widget.dart';
import 'package:dali_ng_pera/tool/dnp_time_tool.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';

import '../../manager/dnp_plugin_manager.dart';
import '../widget/dnp_app_bar.dart';
import '../widget/dnp_dotted_line_widget.dart';
import 'controller/dnp_certification_controller.dart';
import 'dnp_identity_photo_page.dart';
import 'model/dnp_auton_model.dart';

class DnpCertificationPage extends StatefulWidget {
  final String already;

  const DnpCertificationPage({super.key, required this.already});

  @override
  State<DnpCertificationPage> createState() => _DnpCertificationPageState();
}

class _DnpCertificationPageState extends State<DnpCertificationPage> {
  final controller = Get.put(DnpCertificationController());

  @override
  void initState() {
    super.initState();
    controller.onRequestData(widget.already);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: DnpLifecycleWidget(
        ctx: context,
        show: () {
          controller.onRequestData(widget.already);
        },
        subWidget: Container(
          height: double.infinity,
          decoration: const BoxDecoration(
            image: DecorationImage(
              image: AssetImage('assets/images/ic_certification_bg.webp'),
              fit: BoxFit.cover,
            ),
          ),
          child: Column(
            children: [
              Obx(() => DnpAppBar(title: controller.enwrapped?.tossing ?? "")),
              Expanded(
                child: SingleChildScrollView(
                  child: buildContent(),
                ),
              ),
              _buildAgreementText(),
              _buildAgreementButton(),
            ],
          ),
        ),
      ),
    );
  }

  Widget buildContent() {
    return Column(
      children: [
        _buildTopContent(),
        _buildTitle(),
        _buildCertificationContent(),
      ],
    );
  }

  Widget _buildTopContent() {
    return Stack(
      children: [
        Image.asset(
          'assets/images/ic_certification_top_content_bg.webp',
          width: double.infinity,
          height: 208,
        ),
        Positioned(
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          child: Column(
            children: [
              SizedBox(
                height: 19,
              ),
              Obx(() => Text(
                    controller.enwrapped?.buying ?? "",
                    style: TextStyle(
                        fontSize: 14,
                        color: Color(0xFFC1C1C1),
                        fontWeight: FontWeight.w500),
                  )),
              SizedBox(
                height: 9,
              ),
              _buildCenterMoney(),
              SizedBox(
                height: 12,
              ),
              _buildCenterButton(),
            ],
          ),
        )
      ],
    );
  }

  Widget _buildCenterMoney() {
    return SizedBox(
      height: 58,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Obx(() => Text(
                "${controller.enwrapped?.bulky ?? ""}",
                style: TextStyle(
                    fontSize: 48,
                    color: Color(0xFF252630),
                    fontWeight: FontWeight.w600),
              )),
          SizedBox(
            width: 3,
          ),
          Obx(() => Text(
                "${controller.enwrapped?.soundly ?? ""}",
                style: TextStyle(
                    fontSize: 48,
                    color: Color(0xFF252630),
                    fontWeight: FontWeight.w900),
              )),
        ],
      ),
    );
  }

  Widget _buildCenterButton() {
    return Row(
      children: [
        SizedBox(
          width: 34,
        ),
        Obx(() => _buildCenterButtonItem(
            "${controller.hastily?.discernible ?? ""}",
            "${controller.hastily?.respond ?? ""}")),
        SizedBox(
          width: 12,
        ),
        Obx(() => _buildCenterButtonItem("${controller.tea?.discernible ?? ""}",
            "${controller.tea?.respond ?? ""}")),
        SizedBox(
          width: 34,
        ),
      ],
    );
  }

  Widget _buildCenterButtonItem(String title, String content) {
    return Expanded(
        child: Container(
      height: 56,
      width: double.infinity,
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border.all(color: Color(0xFF0193FE), width: 1),
        borderRadius: BorderRadius.circular(56),
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text(
            title,
            style: TextStyle(fontSize: 14, color: Color(0xFF252630)),
          ),
          Text(
            content,
            style: TextStyle(
                fontSize: 16,
                color: Color(0xFF252630),
                fontWeight: FontWeight.w600),
          ),
        ],
      ),
    ));
  }

  Widget _buildTitle() {
    return Container(
      alignment: Alignment.centerLeft,
      margin: EdgeInsets.only(left: 14, right: 14),
      child: Text(
        "Certification condition",
        style: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.w600,
            color: Color(0xFF252630)),
      ),
    );
  }

  Widget _buildCertificationContent() {
    final leftHeight = 466.0;
    final rightHeight = 306.0;
    final spaceTopHeight = (leftHeight - rightHeight) / 2;
    return Container(
      margin: EdgeInsets.only(left: 14, right: 14, top: 12),
      child: Obx(() => Row(
            children: [
              Column(
                children: [
                  GestureDetector(
                    onTap: () {
                      onTapDeveloping(0);
                    },
                    child:
                        _buildCertificationItem(true, controller.crossList[0]),
                  ),
                  SizedBox(
                    height: 14,
                  ),
                  GestureDetector(
                    onTap: () {
                      onTapDeveloping(2);
                    },
                    child:
                        _buildCertificationItem(true, controller.crossList[2]),
                  ),
                  SizedBox(
                    height: 14,
                  ),
                  GestureDetector(
                    onTap: () {
                      onTapDeveloping(4);
                    },
                    child:
                        _buildCertificationItem(true, controller.crossList[4]),
                  ),
                ],
              ),
              Spacer(),
              Container(
                width: 13,
                height: leftHeight,
                child: Column(
                  children: [
                    const SizedBox(
                      height: 7.5,
                    ),
                    Image.asset(
                      controller.crossList[0].proportions == 1
                          ? "assets/images/ic_certification_split_select_icon.png"
                          : "assets/images/ic_certification_split_no_select_icon.png",
                      width: 13,
                      height: 13,
                    ),
                    DnpDottedLineWidget(
                      height: spaceTopHeight - 13,
                      color: Color(0xFF1D4AC8),
                      strokeWidth: 2,
                    ),
                    Image.asset(
                      controller.crossList[1].proportions == 1
                          ? "assets/images/ic_certification_split_select_icon.png"
                          : "assets/images/ic_certification_split_no_select_icon.png",
                      width: 13,
                      height: 13,
                    ),
                    DnpDottedLineWidget(
                      height: spaceTopHeight - 13,
                      color: Color(0xFF1D4AC8),
                      strokeWidth: 2,
                    ),
                    Image.asset(
                      controller.crossList[2].proportions == 1
                          ? "assets/images/ic_certification_split_select_icon.png"
                          : "assets/images/ic_certification_split_no_select_icon.png",
                      width: 13,
                      height: 13,
                    ),
                    DnpDottedLineWidget(
                      height: spaceTopHeight - 13,
                      color: Color(0xFF1D4AC8),
                      strokeWidth: 2,
                    ),
                    Image.asset(
                      controller.crossList[3].proportions == 1
                          ? "assets/images/ic_certification_split_select_icon.png"
                          : "assets/images/ic_certification_split_no_select_icon.png",
                      width: 13,
                      height: 13,
                    ),
                    DnpDottedLineWidget(
                      height: spaceTopHeight - 13,
                      color: Color(0xFF1D4AC8),
                      strokeWidth: 2,
                    ),
                    Image.asset(
                      controller.crossList[4].proportions == 1
                          ? "assets/images/ic_certification_split_select_icon.png"
                          : "assets/images/ic_certification_split_no_select_icon.png",
                      width: 13,
                      height: 13,
                    ),
                  ],
                ),
              ),
              Spacer(),
              Column(
                children: [
                  GestureDetector(
                    onTap: () {
                      onTapDeveloping(1);
                    },
                    child:
                        _buildCertificationItem(false, controller.crossList[1]),
                  ),
                  SizedBox(
                    height: 14,
                  ),
                  GestureDetector(
                    onTap: () {
                      onTapDeveloping(3);
                    },
                    child:
                        _buildCertificationItem(false, controller.crossList[3]),
                  ),
                ],
              )
            ],
          )),
    );
  }

  Widget _buildCertificationItem(bool isLeft, DnpCrossItem model) {
    return SizedBox(
      width: 160,
      height: 132 + 14,
      child: Stack(
        children: [
          Positioned(
              left: isLeft ? 0 : null,
              bottom: 0,
              right: isLeft ? null : 0,
              child: Container(
                width: 148,
                height: 132,
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(10),
                ),
                child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Image.network(
                        model.apostate ?? "",
                        width: 38,
                        height: 38,
                        loadingBuilder: (context, child, loadingProgress) {
                          return Image.asset(
                            model.apostate ?? "",
                            width: 38,
                            height: 38,
                          );
                        },
                        errorBuilder: (context, error, stackTrace) {
                          return SizedBox(
                            width: 38,
                            height: 38,
                          );
                        },
                      ),
                      SizedBox(
                        height: 10,
                      ),
                      Text(
                        model.discernible ?? "",
                        textAlign: TextAlign.center,
                        style: TextStyle(
                            fontSize: 14,
                            fontWeight: FontWeight.w500,
                            color: Color(0xFF252630)),
                      ),
                    ]),
              )),
          Positioned(
              left: isLeft ? null : 0,
              top: 0,
              right: isLeft ? 0 : null,
              child: SizedBox(
                width: 23 + 90,
                height: 28,
                child: Row(
                  children: [
                    if (isLeft) ...[
                      Image.asset(
                        model.proportions == 1
                            ? "assets/images/ic_certification_completed_left_arrow.png"
                            : "assets/images/ic_certification_left_arrow.png",
                        width: 19,
                        height: 22,
                      )
                    ],
                    Container(
                      width: 90,
                      height: 28,
                      decoration: BoxDecoration(
                          color: model.proportions == 1
                              ? Color(0xFF1D4AC8)
                              : Color(0xFFE6E6E6),
                          borderRadius: BorderRadius.circular(15)),
                      child: Center(
                        child: Text(
                          model.proportions == 1 ? "Completed" : "Unfinished",
                          style: TextStyle(
                              fontSize: 14,
                              color: model.proportions == 1
                                  ? Colors.white
                                  : Color(0xFFABABAB),
                              fontWeight: FontWeight.w400),
                        ),
                      ),
                    ),
                    if (!isLeft) ...[
                      RotatedBox(
                        quarterTurns: 2,
                        child: Image.asset(
                          model.proportions == 1
                              ? "assets/images/ic_certification_completed_left_arrow.png"
                              : "assets/images/ic_certification_left_arrow.png",
                          width: 19,
                          height: 22,
                        ),
                      )
                    ]
                  ],
                ),
              )),
        ],
      ),
    );
  }

  Widget _buildAgreementText() {
    return Obx(() {
      String discernible =
          controller.autonModel.value.placing?.discernible ?? "";
      if (discernible.isEmpty) {
        return SizedBox.shrink();
      }
      List<String> list = discernible.split("||");
      if (list.isEmpty) {
        return SizedBox.shrink();
      }
      return Container(
          margin: EdgeInsets.only(left: 14, right: 14, top: 12),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Obx(() => GestureDetector(
                    onTap: () {
                      controller.agreementCheck.value =
                          !controller.agreementCheck.value;
                    },
                    behavior: HitTestBehavior.translucent,
                    child: Image.asset(
                      'assets/images/ic_base_${controller.agreementCheck.value ? 'checkbox' : 'uncheckbox'}.webp',
                      width: 18,
                      height: 18,
                    ),
                  )),
              const SizedBox(
                width: 4,
              ),
              Expanded(
                child: RichText(
                    text: TextSpan(children: [
                  TextSpan(
                    text: list[0],
                    style: TextStyle(
                        fontSize: 14,
                        color: Color(0xFFABABAB),
                        fontWeight: FontWeight.w400),
                  ),
                  if (list.length > 1) ...[
                    WidgetSpan(
                        child: GestureDetector(
                      onTap: () {
                        Get.to(DnpBrowserPage(
                            path:
                                controller.autonModel.value.placing?.several ??
                                    ""));
                      },
                      child: Text(
                        list[1],
                        style: TextStyle(
                          decoration: TextDecoration.underline,
                          fontWeight: FontWeight.w500,
                          fontSize: 14,
                          color: Color(0xFF252630),
                        ),
                      ),
                    ))
                  ]
                ])),
              ),
              const SizedBox(
                width: 4,
              ),
            ],
          ));
    });
  }

  Widget _buildAgreementButton() {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () {
        onTap(
          controller.autonModel.value.boldly?.developing ?? "",
          controller.autonModel.value.boldly?.belated ?? "",
          controller.autonModel.value.boldly?.discernible ?? "",
        );
      },
      child: Container(
        width: double.infinity,
        height: 48,
        alignment: Alignment.center,
        margin: EdgeInsets.only(left: 24, right: 24, top: 14, bottom: 34),
        decoration: BoxDecoration(
            color: Color(0xFF1D4AC8), borderRadius: BorderRadius.circular(10)),
        child: Obx(() => Text(controller.enwrapped?.earnestly ?? "",
            style: TextStyle(
                fontSize: 16,
                color: Colors.white,
                fontWeight: FontWeight.w600))),
      ),
    );
  }

  void onTapDeveloping(int index) {
    if (controller.crossList[index].proportions == 1) {
      onTap(controller.crossList[index].developing ?? "",
          controller.crossList[index].belated ?? "",controller.crossList[index].discernible ?? "");
    } else {
      onTap(
        controller.autonModel.value.boldly?.developing ?? "",
        controller.autonModel.value.boldly?.belated ?? "",
        controller.autonModel.value.boldly?.discernible ?? "",
      );
    }
  }

  void onTap(String developing, String belated,String title) {
    if (developing.isEmpty) {
      String ask = "";
      List<String> asks = controller.enwrapped?.asked ?? [];
      if (asks.isNotEmpty) {
        ask = asks[0];
      }
      controller.onRequestPlaceAnOrder(
          controller.enwrapped?.parcel ?? "",
          controller.enwrapped?.soundly?.toString() ?? "",
          ask,
          controller.enwrapped?.yeared?.toString() ?? "", (value) {
        final t = DnpTimeTool.timestamp;
        DnpMob.inexplicable("9", t, t, paid: controller.parcel);
        Get.off(DnpBrowserPage(
          path: value,
          needBack: true,
        ));
      });
      return;
    }
    if (!controller.agreementCheck.value) {
      DnpPluginManager().showToast("please read and agree Loan Agreement");
      return;
    }
    DnpCertificationJumpUtils.jump(developing, widget.already, belated,title);
  }
}
